import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../Login/login.css';
import '../../../App.css'
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading } from "antd-mobile";
import { useDispatch } from "react-redux";
import { isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import icon_proof_face_tips from '@/assets/icon_proof_face_tips.png'
import icon_retake from '@/assets/icon_retake.png'
import icon_proof_face_bg from '@/assets/icon_proof_face_bg.png'
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import Compressor from 'compressorjs';
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import { reqSaveEvent, reqSaveFace, reqUploadImage, reqUserState } from "@/store/actions/apiServices";


/**
 * 人脸自拍页
 */
export default function ProofFace() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //选择图片
    const [pictureSelected, setPictureSelected] = useState(null)

    //图片文件
    const [pictureFile, setPictureFile] = useState(null)


    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的用户状态信息
    const [userStateInfo, setUserStateInfo] = useState({})

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            console.log("Launch-signOrderId: " + resObj.signOrderId);
            setUserStateInfo(resObj);

            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            //跳转状态页
            if (isHomeSigning) {
                history.replace('/guide');
                return;

            } else if (isHomeReviewing) {
                history.replace('/review');
                return;

            } else if (isHomeReject) {
                history.replace('/reject');
                return;

            } else if (isHomeLoaning) {
                history.replace('/loaning');
                return;

            } else if (isHomeRepay) {
                history.replace('/repay');
                return;
            }

            //判断下是否已经做完所有认证
            if (resObj.isProofFinish === true) {
                //跳转申请页
                history.replace('/apply');
                return;
            }

            //是否为号码认证
            if (isProofMobile(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/proofmobile');
                return;
            }

            //是否为常用app认证
            if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/prooffrequentlyapps');
                return;
            }

            //是否为人脸认证
            if (isProofFace(resObj.stepTitle)) {
                return;
            }

            if (isProofContact(resObj.stepTitle)) {
                if (window.isSupportContactPicker === true) {
                    history.replace('/proofcontact');
                } else {
                    history.replace('/proofcontactinput');
                }
                return;
            }

            history.replace('/proof');
        }
    };

    const checkUserStateInfo = () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.PROOF_FACE, onReqUserStateCallback);

        } catch (e) {
            console.log(e)
        }
    }

    //请求保存接口
    const doUploadImage = async () => {
        try {
            if (pictureFile) {
                setMaskVisible(true);
                reqSaveEvent("PROOF_FACE_COMMIT_CLICK");
                reqUploadImage(pictureFile, (success, url) => {
                    setMaskVisible(false);

                    if (success && url.length > 0) {
                        doSaveFace(url);
                    } else {
                        setPictureSelected(null);
                    }
                });
            }
        } catch (e) {
            console.log(e)
        }
    }

    //请求保存接口
    const doSaveFace = (url) => {
        try {
            if (url.length > 0) {
                setMaskVisible(true);
                reqSaveFace(url, (success, resObj) => {
                    setMaskVisible(false);
                    if (success) {
                        checkUserStateInfo();
                    }
                });
            }
        } catch (e) {
            console.log(e)
        }
    }

    //点击提交
    const onHandleSubmit = async () => {
        try {
            if (pictureFile) {
                doUploadImage()
            } else {
                onHandleImagePick()
            }

        } catch (e) {
            console.log(e)
        }
    }

    //点击返回
    const onHandleNavGoBack = () => {
        history.replace('/home');
    }

    //点击拍照
    const onHandleImagePick = () => {
        const customCameraInput = document.getElementById('loanSaladProofFaceImageInput');
        setTimeout(() => {
            customCameraInput.click()
        }, 200);
    }

    //拍照返回
    const onHandleImageUpload = (event) => {
        console.log("onHandleImageUpload")
        //更新图片文件
        const file = event.target.files[0];
        console.log(file)

        if (file) {
            console.log("file size " + file.size)
            let quality = 0.4
            if (file.size < 1000 * 1000) { //小于1M
                quality = 0.6
            } else if (file.size < 2000 * 1000) { //小于5M
                quality = 0.4
            } else if (file.size < 10000 * 1000) { //小于10M
                quality = 0.2
            } else { //大于10M
                quality = 0.1
            }

            console.log("quality: " + quality)

            new Compressor(file, {
                quality: quality,
                success(result) {
                    console.log("result file size " + result.size)
                    setPictureFile(result)
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        setPictureSelected(reader.result)
                    };
                    reader.readAsDataURL(result);
                }
            })
        } else {
            setPictureSelected(null)
        }
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        setAddHomeMaskVisible(false)
    }

    //启动时请求首页额度
    useEffect(() => {
        reqSaveEvent("PROOF_FACE_START")
        checkUserStateInfo();

        return () => {
            reqSaveEvent("PROOF_FACE_END")
        }
    }, [])

    return (
        <div className="proofRoot">
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>
            <div className="proofContent proofTopMargin0Px">

                <div className="proofFace">

                    <input className="proofFaceImageInput"
                        id="loanSaladProofFaceImageInput"
                        type="file"
                        accept="image/*"
                        capture="user"
                        onChange={onHandleImageUpload} />

                    <span className="proofFaceHeaderTitle proofBottomMargin10Px">Take a selfie, make sure your face is clearly and well it.</span>

                    {(!pictureSelected) && <div className="proofFaceImageContent" onClick={onHandleImagePick}>
                        <img className="proofFaceImagePlaceholder" src={icon_proof_face_bg} alt="" />
                    </div>}

                    {pictureSelected && <div className="proofFaceImageContent">

                        <img className="proofFaceImageResult" src={pictureSelected} alt="" />

                        <div className="proofFaceImageDeleteContent" onClick={onHandleImagePick}>
                            <img className="proofFaceImageDelete" src={icon_retake} alt="" />
                        </div>
                    </div>}

                    <div className="rowAlignStartFullWidth proofBottomMargin30Px proofHorPadding16Px proofTopMargin40Px">
                        <div className="proofFaceTipsContent">
                            <div className="proofFaceTipsRowIcon">
                                <img className="proofFaceIconTips proofRightMargin6Px" src={icon_proof_face_tips} alt="" />
                                <span className="proofFaceTitle">Tips:</span>
                            </div>
                            <div className="proofFaceLine proofTopMargin16Px proofBottomMargin10Px" ></div>
                            <span className="proofFaceTips proofTopMargin10Px">1.No shadow on the face</span>
                            <span className="proofFaceTips proofTopMargin6Px">2.Don't be in a backlit environment</span>
                            <span className="proofFaceTips proofTopMargin6Px">3.Don't wear a mask</span>
                            <span className="proofFaceTips proofTopMargin6Px">4.Please show your forehead</span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="proofApplyBtn">
                <div className="mainButtonGradient" onClick={onHandleSubmit}>{pictureSelected ? 'Confirm and submit' : 'Start selfie'}</div>

                {!pictureSelected && <input className="proofFaceImageInputSubmit"
                    id="loanSaladProofFaceImageInputSubmit"
                    type="file"
                    accept="image/*"
                    capture="user"
                    onChange={onHandleImageUpload} />
                }
            </div>

            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Privacy policy" />

            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}